package com.java.simple.study.juc.p5;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author zhoujunlin
 * @date 2022年06月27日 21:42
 * @desc
 */
public class AccountAtomicInteger implements Account {
    private final AtomicInteger balance;

    public AccountAtomicInteger(Integer balance) {
        this.balance = new AtomicInteger(balance);
    }

    @Override
    public Integer getBalance() {
        return balance.get();
    }

    @Override
    public void withdraw(Integer amount) {
        //balance.addAndGet(-1 * amount);
        // 与下面方法等价
        while (true) {
            int prev = balance.get();
            int next = prev - amount;
            if (balance.compareAndSet(prev, next)) {
                break;
            }
        }
    }

    public static void main(String[] args) {
        Account.demo(new AccountAtomicInteger(10000));
        //剩余:0 cost:135 ms
    }

}
